import { defineStore } from 'pinia'
import { login as apiLogin } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : null,
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.user && state.user.role === 'admin',
    isTeacher: (state) => state.user && state.user.role === 'teacher',
    isStudent: (state) => state.user && state.user.role === 'student',
    getUserRole: (state) => state.user ? state.user.role : null,
    getUserRoleText: (state) => {
      if (!state.user) return ''
      switch (state.user.role) {
        case 'admin': return '管理员'
        case 'student': return '学生'
        case 'teacher': return '教师'
        default: return ''
      }
    },
  },
  
  actions: {
    async login(username, password) {
      try {
        const response = await apiLogin({ username, password })
        // 后端返回格式: { success: true, token: "...", data: { user: {...} } }
        this.token = response.token
        this.user = response.data.user
        localStorage.setItem('token', this.token)
        localStorage.setItem('user', JSON.stringify(this.user))
        return true
      } catch (error) {
        console.error('Store: 登录失败:', error)
        return false
      }
    },
    
    logout() {
      this.token = null
      this.user = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      // 可选：清除其他 store 的状态
    },
    
    // 从本地存储恢复用户状态，防止刷新丢失
    initializeStore() {
      const token = localStorage.getItem('token')
      const userStr = localStorage.getItem('user')
      
      if (token) {
        this.token = token
      }
      if (userStr) {
        this.user = JSON.parse(userStr)
      }
    }
  }
}) 